package com.sloth.bear.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sloth.bear.dto.base.Response;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应处理器 - 自动包装返回结果为Result格式
 */
@RequiredArgsConstructor
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 跳过已经是Result类型的返回值、ResponseEntity类型
        if (returnType.getParameterType().equals(Response.class)
                || returnType.getParameterType().equals(ResponseEntity.class)) {
            return false;
        }
        
        
        // 跳过void返回类型
        if (returnType.getParameterType().equals(void.class) || returnType.getParameterType().equals(Void.class)) {
            return false;
        }
        
        return true;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        
        // 如果返回值是String类型，需要特殊处理
        if (body instanceof String) {
            return objectMapper.writeValueAsString(Response.success(body));
        }
        
        return Response.success(body);
    }
}